<template>
    <a-modal title="办理任务" :visible="show" width="100%" wrapClassName="full-modal" :confirm-loading="modalLoading"
        @ok="modalOk" @cancel="modalCancel">
        <div>
            <!-- 页签上方的按钮 -->
            <div class="flowBtn">
                <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    保存
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    提交
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    退回
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    挂起
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    终止
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    指派
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    同意
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    拒绝
                  </a-button>
                  <a-button type="primary" @click="triggerSaveOnAllPages">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    转办
                  </a-button>
                <!-- <button @click="triggerMethodOnAllPages">触发所有页面的方法</button>
                <button @click="triggerSaveOnAllPages">触发所有页面的方法</button> -->
            </div>
            <a-tabs v-model:activeKey="activeTabKey">
                <a-tab-pane :tab="item.title" :key="item.fullPath" style="height: calc(100vh - 245px);"
                    v-for="(item, index) in tabList">
                    <keep-alive :max="5">
                        <component :is="item.component" :key="item.fullPath"
                            :params="param"
                            :pageParams="item"
                            :ref="(el) => setChildRef(el, item.fullPath)" @vue:mounted="(el) => handleChildMethod(el)"
                            @vue:unmounted="(el) => handleChildMethod(el)" />
                    </keep-alive>
                </a-tab-pane>
            </a-tabs>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
import { markRaw, defineAsyncComponent, resolveComponent, defineProps, watch, ref, defineEmits, onBeforeUnmount, shallowRef, onMounted } from 'vue';
import { getNodeFormData } from '@/api/workflow/innerform';
import { forEach } from 'lodash';
import { useRoute, useRouter, RouteLocationNormalizedLoaded } from 'vue-router';
import { DownloadOutlined } from '@ant-design/icons-vue';
import { resolve } from 'path';
interface TabItem {
    fullPath: string;
    name: string;
    title: string;
    component: string | any;
    id:string;
    formId:string;
    businessKey:string;
}
const route = useRoute()
// 弹框路由loading
let modalLoading = ref(false);
// 弹框显隐
let show = ref(false);

// 定义接收的属性
const props = defineProps({
    visible: Boolean,
    taskDefinitionKey: String,
    processInstanceId: String
});

const param = ref({
    taskDefinitionKey: props.taskDefinitionKey,
    processInstanceId: props.processInstanceId
})

// 定义向外触发的事件
const emits = defineEmits(['update:visible']);
//const modules = import.meta.glob('../views/**/*.{vue,tsx}');
// 监听 visible 属性的变化
watch(() => props.visible, (newValue) => {
    tabList.value = [];
    show.value = newValue;
    if (newValue == true) {
        getNodeFormData({ NodeId: props.taskDefinitionKey }).then(e => {
            let data = e.data.Data;
            data = data.sort((a, b) => a.SortNum - b.SortNum);
            forEach(data, (item) => {
                let viewPath = "/src";
                if(item.FormType==1){
                    viewPath = viewPath + item.FormPath;
                } else{
                    viewPath = viewPath + "/views/workbenches/customeForm.vue";
                }
                tabList.value.push({
                    fullPath: item.FormPath,
                    name: item.FormName,
                    title: item.FormName,
                    id: item.Id,
                    formId: item.FormId,
                    businessKey: item.BusinessKey,
                    component: defineAsyncComponent(() =>
                        import(viewPath)
                    )
                })
            })

            param.value = {
                taskDefinitionKey: props.taskDefinitionKey ,
                processInstanceId: props.processInstanceId
            }
            // 初始化激活的标签页
            if (tabList.value.length > 0) {
                activeTabKey.value = tabList.value[0].fullPath;
            }
        }).catch(e => {
            console.log(e);
        })
    }
});

const loadModule = async (path: any) => {
    // import 后面是文件路径
    const module = await import(path);
    return module.default;
}

const registerComponent = (componentPath: string) => {
    for (const item in modules) {
        if (item.includes(componentPath)) {
            return defineAsyncComponent(modules[item]);
        }
    }
};
// @desc: 弹框确认事件(回调)
const modalOk = () => {
    emits('ok');
    emits('update:visible', false); // 关闭模态框
}
// @desc: 弹框取消事件(回调)
const modalCancel = () => {
    emits('cancel')
    emits('update:visible', false); // 关闭模态框
    modalLoading.value = false
}

// 当前激活的标签页
const activeTabKey = ref('');

// 动态加载示例
const tabList = ref<TabItem[]>([
    //   {
    //     fullPath: '/dynamic-page',
    //     name: 'DynamicPage',
    //     title: '动态页面',
    //     component: defineAsyncComponent(() => 
    //       import('@/views/workbenches/page2.vue')
    //     )
    //   },
    //   {
    //     fullPath: '/dynamic-page2',
    //     name: 'DynamicPage2',
    //     title: '动态页面2',
    //     component: defineAsyncComponent(() => 
    //       import('@/views/workbenches/page1.vue')
    //     )
    //   }
]);
let activeChildren = {};
const setChildRef = (el, fullPath) => {
    if (el) {
        activeChildren[fullPath] = el;
    } else {
        delete activeChildren[fullPath];
    }
}
// 存储所有子组件的引用
const childComponents = ref([]);

// 处理子组件触发的方法
const handleChildMethod = (child: ComponentPublicInstance | null) => {
    if (!child) return;
    childComponents.value.push(child);
    onBeforeUnmount(() => {
        const index = childComponents.value.indexOf(child);
        if (index > -1) {
            childComponents.value.splice(index, 1);
        }
    });
};


// 触发所有页面的方法
const triggerMethodOnAllPages = () => {
    Object.values(activeChildren).forEach(child => {
        if (child.someMethod) { // 替换为实际方法名
            child.someMethod();
        }
    });
};

const triggerSaveOnAllPages = () => {
    Object.values(activeChildren).forEach(child => {
        if (child.Save) { // 替换为实际方法名
            child.Save();
        }
    });
};

</script>

<style lang="scss">
.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;
        // 新增样式，让模态框高度为视口高度
        height: 100vh;
    }

    .ant-modal-body {
        flex: 1;
        // 新增样式，让模态框内容区高度自适应
        height: calc(100% - 55px);
        overflow-y: auto;
    }

    // 调整模态框头部和底部样式，让它们也适应新的布局
    .ant-modal-header,
    .ant-modal-footer {
        flex-shrink: 0;
    }
    
    .flowBtn {
        button {
            margin-left: 10px;
        }
    }

}

/* 覆盖 .ant-tabs-top-content 的 margin-left 样式 */
.ant-tabs-top-content.ant-tabs-content.ant-tabs-content-animated {
    margin-left: 0 !important;
}
</style>